import 'dart:async';
import 'dart:io';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../utils/http_client.dart';
import 'location_service.dart';

class HeartbeatService {
  Timer? _heartbeatTimer;
  final _deviceInfo = DeviceInfoPlugin();
  final _connectivity = Connectivity();
  String? _deviceId;
  String? _jobNumber;

  Future<void> init() async {
    final prefs = await SharedPreferences.getInstance();
    _jobNumber = prefs.getString('jobNumber');
    
    try {
      if (Platform.isAndroid) {
        final androidInfo = await _deviceInfo.androidInfo;
        _deviceId = androidInfo.id;
      } else if (Platform.isIOS) {
        final iosInfo = await _deviceInfo.iosInfo;
        _deviceId = iosInfo.identifierForVendor;
      }
    } catch (e) {
      print('Failed to get device info: $e');
      _deviceId = 'unknown';
    }
  }

  void startHeartbeat() {
    _heartbeatTimer?.cancel();
    _heartbeatTimer = Timer.periodic(const Duration(seconds: 30), (_) {
      _sendHeartbeat();
    });
  }

  void stopHeartbeat() {
    _heartbeatTimer?.cancel();
    _heartbeatTimer = null;
  }

  Future<void> _sendHeartbeat() async {
    try {
      // final position = await LocationService.getCurrentLocation();
      // final connectivityResult = await _connectivity.checkConnectivity();
      //
      // if (position == null || _deviceId == null || _jobNumber == null) {
      //   return;
      // }
      //
      // final networkStatus = connectivityResult != ConnectivityResult.none;
      // final networkType = connectivityResult.name;

      await HttpClient.externalDio.post(
        'https://trying.jinhubianli.com/device/heartbeat',
        data: {
          'deviceId': _deviceId,
          'jobNumber': _jobNumber,
          // 'latitude': position.latitude,
          // 'longitude': position.longitude,
          // 'networkStatus': networkStatus,
          // 'networkType': networkType,
        },
      );
    } catch (e) {
      print('Heartbeat failed: $e');
    }
  }
} 